package com.fsy.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fsy.anno.NoToken;
import com.fsy.entities.MenuInfo;
import com.fsy.entities.Modules;
import com.fsy.entities.Users;
import com.fsy.mapper.UsersMapper;
import com.fsy.service.ModulesService;
import com.fsy.service.UsersService;
import com.fsy.utils.Result;
import com.fsy.utils.TokenUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Resource
    private UsersService usersService;

    @Resource
    private ModulesService modulesService;

    @Resource
    private UsersMapper usersMapper;


    @Resource
    private RedisTemplate redisTemplate;//注入redis

    /**
     * 登录
     * @param users
     * @return
     */
    @PostMapping("/login")
    @NoToken //不拦截登录
    public Map<String, Object> login(Users users) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("loginName",users.getLoginName()).eq("password",users.getPassword());
        Users u = usersService.getOne(wrapper);
        Map<String ,Object> rslmap = new HashMap<>();
        if (u==null){
            return Result.toClient("1","用户名不存在");
        }else {
            QueryWrapper<Users> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("loginName", users.getLoginName())
                    .eq("password", users.getPassword());
            Users usersPassword = usersService.getOne(wrapper1);
            if (usersPassword==null){
                usersService.incorrecPassword(u.getId());
                return Result.toClient("1","密码输入错误");
            }
        }
        if(u.getIsLockout() !=0){
            return Result.toClient("1","账户已锁定");
        }
        if(u!=null){
            //生成token
            String token = "";
            try{
                token =  TokenUtil.sign(u,60*30*1000);
            }catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }catch (JsonProcessingException e){
                e.printStackTrace();
            }
            //登录成功
            rslmap.put("code","0");
            rslmap.put("token",token); //返回token给前端
        }else{
            //登录成功
            rslmap.put("code","1");
        }
        return rslmap;
    }

    //使用条件构造器：分页查询

    /**
     *根据条件查询用户
     * @param users
     * @return
     */
    @GetMapping("/findByUsers")
    public Map<String,Object> findByUsers(Users users){
        //查询全部用户信息
        List<Users> usersList = usersService.selectUsers(users);
        //查询全部用户数量
        int count = usersService.selectCounts(users);
        return Result.toClient("0", "",count,usersList);
    }

    /**
     * 修改按钮开关
     * @param users
     * @return
     */
    @PostMapping("/editcheck")
    public Map<String,Object> editcheck(Users users){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dqsj  = df.format(new Date());
        int number = users.getValid().equals("on") ? 1 : 0;
        if(number ==1){
            users.setLockTime(dqsj);
        }
        users.setIsLockout(number);
        Users users1 = usersMapper.selectById(users.getId());
        if (users1.getLoginName().equals("admin")){
            return Result.toClient("1","管理员账户不可被锁定");
        }
        boolean rel = usersService.updateById(users);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","修改成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","修改失败");
        }
        return rslmap;
    }

    /**
     * 添加用户
     * @param users
     * @return
     */
    @PostMapping("/insertUsers")
    public Map<String,Object> insertUsers(Users users){
        List<Users> list = usersService.list();
        for (int i=0;i<list.size();i++){
            if(users.getLoginName().equals(list.get(i).getLoginName())){
                return Result.toClient("1", "已有用户使用此用户名");
            }
        }
        Boolean rel = usersService.save(users);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","添加成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","添加失败");
        }
        return rslmap;
    }

    /**
     *删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Map<String ,Object> deleteById(@PathVariable Integer id,Users users){
        Users users1 = usersMapper.selectById(users.getId());
        if (users1.getLoginName().equals("admin")){
            return Result.toClient("1","管理员账户不能被删除");
        }
        boolean rel = usersService.removeById(id);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","删除成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","删除失败");
        }
        return rslmap;
    }

    /**
     * 修改用户信息
     * @param users
     * @return
     */
    @PostMapping("/updateById")
    public Map<String,Object> updateById(Users users){
        Boolean rel = usersService.updateById(users);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","修改成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","修改失败");
        }
        return rslmap;
    }

    //修改密码
    @PostMapping("/updatePwd")
    public Map<String,Object> updatePassword(String password,Integer id,String old_password,String again_password){
        Map<String,Object> map=new HashMap<>();
        Users users = usersMapper.selectById(id);
        if (!old_password.equals(users.getPassword())){
            return Result.toClient("1","旧密码输入错误");
        }
        if (!again_password.equals(password)){
            return Result.toClient("1","两次新密码输入不一致");
        }
        if(again_password.equals(old_password)){
            return Result.toClient("1","旧密码不能和新密码相同");
        }
        UpdateWrapper<Users> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("password",password)
                .eq("id",id);
        boolean rsl = usersService.update(updateWrapper);
        if (rsl){
            map.put("code","0");
            map.put("msg","修改密码成功");
        }else {
            map.put("code","1");
            map.put("msg","修改密码失败");
        }
        return map;
    }



    /**
     * 重置密码
     * @param users
     * @return
     */
    @PostMapping("/updatePasswordById")
    public Map<String,Object> updatePasswordById(Users users) {
        users.setPassword("ff123");
        Users users1 = usersMapper.selectById(users.getId());
        if (users1.getLoginName().equals("admin")){
            return Result.toClient("1","管理员账户不能被重置密码");
        }
        boolean rel = usersService.updateById(users);
        Map<String ,Object> rslmap =new HashMap<>();
        if (rel){
            rslmap.put("code","0");
            rslmap.put("msg","重置密码成功");
        }else{
            rslmap.put("code","1");
            rslmap.put("msg","重置密码失败");
        }
        return rslmap;
    }

    @PostMapping("/login1")
    @NoToken
    public Map<String,Object> findUser(String loginName, String password){
        //获取请求参数
        //String imageText = request.getParameter("image");
        //图片的验证码
        //String text = (String) request.getSession().getAttribute("text");
        /*if(!text.equalsIgnoreCase(imageText)){
            request.setAttribute("imageMess", "验证码输入错误!");
        }*/
        //判断用户是否存在
        QueryWrapper<Users> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("loginName",loginName);
        Users u = usersService.getOne(queryWrapper1);
        if (u == null ){
            //返回并给出提示
            return Result.toClient("1","该用户不存在");
        }

        //判断是否锁定
        if (u.getIsLockout() == 1){
            //返回并给提示
            return Result.toClient("1","该用户已锁定，请联系系统管理员！");
        }
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loginName",loginName).eq("password",password);
        Users loginUser = usersService.getOne(queryWrapper);
        if (loginUser == null){
            //密码错误，记录错误次数
            String count = (String) redisTemplate.opsForValue().get(loginName);//从redis里取错误次数

            if (StringUtils.isEmpty(count)){
                //如果娶不到，说明是第一次密码错误
                count = "1";
            } else {
                //如果能取到说明不是第一次
                count = (Integer.parseInt(count) + 1)+"";
            }
            redisTemplate.opsForValue().set(loginName,count);
            //当前次数达到3，锁定
            if(Integer.parseInt(count) == 3){
                //锁定用户 update users set isLockOut = 1 where loginName = xx and password = xxx
                /*UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("isLockOut",1)
                        .eq("loginName",loginName);
                usersService.update(updateWrapper);*/
                u.setIsLockout(1);
                usersService.updateById(u);
                //删除redis里对应的key
                redisTemplate.delete(loginName);
            }
            //返回并给提示
            return Result.toClient("1","密码不对，当前错误次数"+count+",达到3次自动锁定");

        }

        //获取该用户对应的按钮权限（给第三步按钮权限用），并返回给页面
        //1.获取该用户拥有所有的按钮的权限
        List<MenuInfo> opsList = modulesService.initMenu(loginUser.getId(),"b");
        String buttonPermission="";
        for (MenuInfo m : opsList){
            buttonPermission += m.getOps()+"|";
        }

        //获取当前用户的权限，即获取该用户能操作的模块（写sql）
        List<Modules> permission = usersService.getPermission(loginName,password);
        //登录成功买吧权限返回给页面
        Map<String,Object> rslMap = new HashMap<>();
        rslMap.put("code","0");
        rslMap.put("msg","登录成功");
        rslMap.put("buttonPermission",buttonPermission); //按钮权限
        //rslMap.put("permission",permission); //按钮权限
        rslMap.put("userId",loginUser.getId());//返回用户id给页面
        //生成token返回给页面
        String token = "";
        try{
            token =  TokenUtil.sign(u,60*30*1000);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        rslMap.put("token",token); //返回token给前端
        rslMap.put("loginName",loginUser.getLoginName());//返回用户id给页面
        return rslMap;
    }



}
